package com.angcyo.selenium.auto.action

import com.angcyo.javafx.base.ex.syncBack
import com.angcyo.library.ex.count
import com.angcyo.selenium.auto.BaseControl
import com.angcyo.selenium.auto.controller.dslPutStage
import com.angcyo.selenium.bean.putMap
import com.angcyo.selenium.auto.parse.HandleResult
import com.angcyo.selenium.auto.parse.args
import com.angcyo.selenium.bean.ActionBean
import org.openqa.selenium.WebElement

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2021/01/18
 */
class PutTextAction : BaseCodeAction() {

    override fun interceptAction(control: BaseControl, action: String?): Boolean {
        return action?.startsWith(Action.ACTION_PUT_TEXT) == true
    }

    override fun runAction(
        control: BaseControl,
        element: WebElement,
        actionBean: ActionBean,
        action: String
    ): HandleResult {
        val result = HandleResult()
        result.elementList = listOf(element)

        //解析参数
        var key = "putText"
        var title = "输入内容"
        var label = "请输入内容:"
        var promptText = "需要输入的内容"
        var tip: String? = null

        if (action.count(' ') > 0) {
            //如果包含了空格, 则使用最新的正则参数解析方法.
            title = action.arg("title")?.run { control._autoParse.parseText(control, this).firstOrNull() } ?: title
            key = action.arg("key") ?: key
            label = action.arg("label")?.run { control._autoParse.parseText(control, this).firstOrNull() } ?: label
            promptText =
                action.arg("prompt")?.run { control._autoParse.parseText(control, this).firstOrNull() } ?: promptText
            tip = action.arg("tip")?.run { control._autoParse.parseText(control, this).firstOrNull() }
        } else {
            action.args { index, str ->
                when (index) {
                    1 -> key = str
                }
            }
        }

        val value = syncBack { dslPutStage(title, label, promptText, tip) }
        result.success = value != null

        if (result.success) {
            //保存起来
            control._currentTaskBean?.putMap(key, value)
        }

        control.logAction?.invoke("手动输入:[${title}][$value]:${result.success}")
        return result
    }
}